
<template>
  <el-form
    v-if="form"
    :ref="refName"
    :model="form"
    :size="size"
    :rules="rules"
    :label-suffix="labelSuffix"
    :label-position="labelPosition"
    :label-width="labelWidth"
    @submit.native.prevent
  >
    <el-form-item
      prop="name"
      label="模板名称"
      class="form-item--medium"
    >
      <el-input
        ref="formInput.name"
        v-model="form.name"
      />
    </el-form-item>
    <el-form-item
      prop="description"
      label="描述备注"
      class="form-item--medium"
    >
      <el-input
        v-model="form.description"
        type="textarea"
      />
    </el-form-item>
    <el-form-item
      prop="deliver_period"
      label="发货周期"
    >
      <el-select
        ref="formInput.deliver_period"
        v-model="form.deliver_period"
        placeholder="请选择发货周期"
      >
        <el-option
          v-for="item in deliverPeriods"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <div class="form-item__tips transform-smaller">
        如实设定宝贝的发货时间，可避免发货咨询和纠纷
      </div>
    </el-form-item>
    <el-form-item
      prop="pricing_mode"
      label="计价方式"
    >
      <el-radio-group v-model="form.pricing_mode">
        <el-radio
          v-for="(mode,index) in pricingModes"
          :key="index"
          :label="mode.value"
          border
        >
          {{ `按${mode.label}计费` }}
        </el-radio>
      </el-radio-group>
    </el-form-item>

    <form-group
      title="默认配送运费设置"
      :content-layout="size==='small'?'grid':''"
    >

      <el-form-item
        :label="`首${pricingMode.label}（${pricingMode.unit}）`"
        prop="quantity"
      >
        <el-input-number
          v-model="form.quantity"
          :step="1"
          :min="1"
          step-strictly
        />
      </el-form-item>
      <el-form-item
        :label="`首${pricingMode.label}运费（元）`"
        prop="price"
      >
        <el-input-number
          v-model="form.price"
          :controls="false"
          :min="0"
        />
      </el-form-item>
      <el-form-item
        :label="`续${pricingMode.label}（${pricingMode.unit}）`"
        prop="increase_quantity"
      >
        <el-input-number
          v-model="form.increase_quantity"
          :step="1"
          :min="1"
          step-strictly
        />
      </el-form-item>
      <el-form-item
        :label="`续${pricingMode.label}运费（元）`"
        prop="increase_price"
      >
        <el-input-number
          v-model="form.increase_price"
          :controls="false"
          :min="0"
        />
      </el-form-item>
      <el-form-item slot="footer">
        <div class="form-item__tips">除指定地区外，其余地区的运费采用“默认配送运费设置”</div>
      </el-form-item>
    </form-group>

    <form-group title="区域配送设置">
      <embargo-area
        v-model="form.disable_areas"
        label="不支持配送地区"
      />
      <el-form-item label="自定义区域运费设置">
        <div>
          <el-button
            type="text"
            @click="onAddMode"
          >添加自定义配送区域</el-button>
        </div>
        <el-table
          v-if="form.modes.length"
          :data="form.modes"
          style="width: 100%"
          class="deliver-area-table"
        >
          <el-table-column
            prop="quantity"
            :label="`首${pricingMode.label}（${pricingMode.unit}）`"
          >
            <el-form-item
              slot-scope="scope"
              :prop="'modes['+scope.$index + '].quantity'"
            >
              <el-input
                v-model.number="scope.row.quantity"
                :placeholder="`首${pricingMode.label}`"
              />
            </el-form-item>
          </el-table-column>
          <el-table-column
            prop="price"
            label="运费（元）"
          >
            <el-form-item
              slot-scope="scope"
              :prop="'modes['+scope.$index + '].price'"
            >
              <el-input
                :ref="`formInput.modes[${scope.$index}].price`"
                v-model.number="scope.row.price"
                :placeholder="`首${pricingMode.label}运费`"
              />
            </el-form-item>
          </el-table-column>
          <el-table-column
            prop="increase_quantity"
            :label="`续${pricingMode.label}（${pricingMode.unit}）`"
          >
            <el-form-item
              slot-scope="scope"
              :prop="'modes['+scope.$index + '].increase_quantity'"
            >
              <el-input
                v-model.number="scope.row.increase_quantity"
                :placeholder="`续${pricingMode.label}`"
              />
            </el-form-item>
          </el-table-column>
          <el-table-column
            prop="increase_price"
            label="续费（元）"
          >
            <el-form-item
              slot-scope="scope"
              :prop="'modes['+scope.$index + '].increase_price'"
            >
              <el-input
                v-model.number="scope.row.increase_price"
                :placeholder="`续${pricingMode.label}运费`"
              />
            </el-form-item>
          </el-table-column>
          <el-table-column
            type="expand"
            label="区域"
          >
            <template slot-scope="props">
              <level-area-cell v-model="props.row.areas" />
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="right"
            label="操作"
            width="92"
          >
            <template slot-scope="scope">
              <deliver-area
                v-model="scope.row.areas"
                button-text="修改"
                label=""
              />
              <el-button
                type="text"
                @click="onDeleteMode(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div
          v-else
          class="form-item__tips"
        >可根据实际物流情况添加相应的配送区域模板</div>
      </el-form-item>
    </form-group>
    <form-action fixed>
      <el-form-item width="300">
        <el-button
          type="primary"
          @click="onSave"
        >{{ submitButtonText }}</el-button>
      </el-form-item>
    </form-action>
  </el-form>
</template>

<script>
import FormGroup from '@/components/Form/FormGroup'
import EmbargoArea from './components/EmbargoArea'
import LevelAreaCell from './components/LevelAreaCell'
import DeliverArea from './components/DeliverArea'
import FormAction from '@/components/Form/FormAction'
export default {
  name: 'FreightForm',
  components: {
    FormGroup,
    EmbargoArea,
    LevelAreaCell,
    DeliverArea,
    FormAction
  },
  props: {
    primaryKey: {
      type: [String, Number],
      default: ''
    },
    labelPosition: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: '20%'
    },
    labelSuffix: {
      type: String,
      default: ''
    },
    refName: {
      type: String,
      default: 'freightForm'
    },
    size: {
      type: String,
      default: ''
    },
    submitButtonText: {
      type: String,
      default: '提交保存'
    }
  },
  data() {
    return {
      deliverPeriods: [],
      pricingModes: [
        {
          value: 0,
          label: '件数',
          unit: '个'
        },
        {
          value: 1,
          label: '重量',
          unit: 'kg'
        },
        {
          value: 2,
          label: '体积',
          unit: 'm³'
        }
      ],
      areas: [],
      form: null,
      rules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        deliver_period: [{ required: true, message: '请设置发货周期', trigger: 'change' }]
      }
    }
  },
  computed: {
    pricingMode() {
      var modeValue = (this.form && this.form.pricing_mode) || 0
      return this.pricingModes.find(item => {
        return item.value === modeValue
      })
    }
  },
  watch: {},
  mounted() {
    this.onLoad()
  },
  methods: {
    onAddMode() {
      var index = `formInput.modes[${this.form.modes.length}].price`
      this.form.modes.push({
        id: 0,
        template_id: 0,
        type: 0,
        areas: [],
        quantity: 1,
        price: 0,
        increase_quantity: 1,
        increase_price: 0
      })
      this.$nextTick(() => {
        var dom = this.$refs[index]
        console.log(dom, this.$refs)
        if (dom) {
          dom.$refs.input && dom.$refs.input.focus()
          dom.$el.scrollIntoView({
            // 滚动到指定节点
            block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
            behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          })
        }
      })
    },
    onDeleteMode(index) {
      this.form.modes.splice(index, 1)
    },
    onLoad() {
      this.$http.shop.updateFreightTemplate(null, this.primaryKey, false).then(res => {
        console.log(res.data)
        const { form, pricingModes, deliverPeriods } = res.data
        this.form = form
        this.pricingModes = pricingModes
        this.deliverPeriods = deliverPeriods
      })
    },
    onSave() {
      this.$refs.freightForm.validate((valid, obj) => {
        if (valid) {
          console.log(this.form)
          this.$http.shop.updateFreightTemplate(this.form, this.primaryKey).then(res => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.$emit('saved', res.data)
          })
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            break
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" >
.form-item__group {
  display: flex;
  flex-direction: column;
  &.el-form-item > .el-form-item__label {
    border-bottom: 1px solid #f6f6f6;
    float: none;
    margin-bottom: 20px;
    text-align: initial;
  }
  &.el-form-item > .el-form-item__content {
    margin: 0;
    display: flex;
    flex-wrap: wrap;
  }
  &.el-form-item .el-form-item {
    margin-bottom: 22px;
    flex: 50%;
    display: flex;
    flex-direction: column;
    .el-form-item__label {
      float: none;
      text-align: initial;
    }
  }
}
.form-group--small {
  .form-group__content {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(auto-fill, calc(50% - 10px));
  }
}
</style>
<style lang="scss" scoped>
.deliver-area-table {
  font-size: 12px;
  ::v-deep .el-table__expand-column {
    .el-table__expand-icon {
      .el-icon-arrow-right:before {
        // 这是展开图标
        content: '\e708';
      }
      &--expanded {
        // 这是点击后的旋转角度
        transform: rotate(0);
        .el-icon-arrow-right:before {
          // 这是展开图标
          content: '\e79e';
        }
      }
    }
  }
}
</style>
